<template>
  <div class="pet-detail-container">
    <el-card v-loading="loading">
      <div slot="header" class="clearfix">
        <span>宠物详情</span>
        <div class="operation-buttons">
          <el-button 
            v-if="canAdopt" 
            type="success" 
            size="small" 
            @click="handleAdopt">
            申请领养
          </el-button>
          <el-button 
            v-if="canCancelAdoption" 
            type="warning" 
            size="small" 
            @click="handleCancelAdoption">
            取消领养
          </el-button>
        </div>
      </div>

      <el-row :gutter="20">
        <el-col :span="8">
          <div class="pet-image">
            <el-image 
              :src="pet.imageUrl ? getImageUrl(pet.imageUrl) : require('@/assets/default-pet.jpg')"
              fit="cover">
            </el-image>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="pet-info">
            <el-descriptions :column="2" border>
              <el-descriptions-item label="宠物名称">{{ pet.name }}</el-descriptions-item>
              <el-descriptions-item label="类别">{{ pet.category }}</el-descriptions-item>
              <el-descriptions-item label="品种">{{ pet.breed }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ pet.age }}岁</el-descriptions-item>
              <el-descriptions-item label="性别">{{ pet.gender }}</el-descriptions-item>
              <el-descriptions-item label="健康状况">{{ pet.healthStatus }}</el-descriptions-item>
              <el-descriptions-item label="领养状态">
                <el-tag :type="pet.adoptionStatus === 'ADOPTED' ? 'success' : 'warning'">
                  {{ pet.adoptionStatus === 'ADOPTED' ? '已领养' : '待领养' }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="主人" v-if="pet.adoptionStatus === 'ADOPTED'">
                {{ pet.ownerName || '未知' }}
              </el-descriptions-item>
            </el-descriptions>
            
            <div class="pet-description">
              <h3>详细描述</h3>
              <p>{{ pet.description }}</p>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 健康记录部分 -->
      <div class="health-records" v-if="pet.id">
        <h3>健康记录</h3>
        <el-table
          :data="healthRecords"
          style="width: 100%"
          v-loading="healthRecordsLoading">
          <el-table-column prop="type" label="类型" width="120"></el-table-column>
          <el-table-column prop="date" label="日期" width="180"></el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
          <el-table-column prop="veterinarian" label="兽医" width="120"></el-table-column>
        </el-table>
      </div>
      
      <!-- 调试信息区域 -->
      <div class="debug-info" v-if="showDebug">
        <h3>调试信息</h3>
        <pre>当前用户: {{ JSON.stringify(userInfo, null, 2) }}</pre>
        <pre>宠物领养状态: {{ pet.adoptionStatus }}</pre>
        <pre>是否可以领养(canAdopt): {{ canAdopt }}</pre>
        <pre>是否可以取消领养(canCancelAdoption): {{ canCancelAdoption }}</pre>
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getPetDetail, adoptPet, cancelAdoption } from '@/api/pet'
import { getHealthRecords } from '@/api/petHealth'

export default {
  name: 'PetDetail',
  data() {
    return {
      loading: false,
      pet: {},
      healthRecords: [],
      healthRecordsLoading: false,
      showDebug: false // 关闭调试信息显示
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo && this.userInfo.role === 'ADMIN'
    },
    isMyPet() {
      return this.userInfo && this.pet.ownerId === this.userInfo.id
    },
    canAdopt() {
      // 简化条件：用户已登录 且 宠物状态为"待领养"
      return this.userInfo && 
             this.pet.adoptionStatus === 'AVAILABLE';
    },
    canCancelAdoption() {
      // 简化条件：(是管理员或是宠物拥有者) 且 宠物状态为"已领养"
      return (this.isAdmin || this.isMyPet) && 
             this.pet.adoptionStatus === 'ADOPTED';
    }
  },
  created() {
    this.fetchPetDetail()
  },
  methods: {
    fetchPetDetail() {
      const id = this.$route.params.id
      this.loading = true
      getPetDetail(id).then(response => {
        if (response.code === 200) {
          console.log('Pet detail response:', response.data)
          
          this.pet = response.data
          
          // 如果宠物已被领养但没有主人名称，尝试从拥有者ID获取用户名
          if (this.pet.adoptionStatus === 'ADOPTED' && !this.pet.ownerName && this.pet.ownerId) {
            console.log('宠物已被领养，但主人名称为空，尝试从ownerId获取: ', this.pet.ownerId)
            
            // 如果当前用户就是拥有者，直接使用当前用户名
            if (this.userInfo && this.pet.ownerId === this.userInfo.id) {
              console.log('设置当前用户为主人: ', this.userInfo.username)
              this.pet.ownerName = this.userInfo.username
            }
          }
          
          console.log('Pet adoptionStatus:', this.pet.adoptionStatus)
          console.log('Pet ownerName:', this.pet.ownerName)
          console.log('Pet ownerId:', this.pet.ownerId)
          console.log('领养按钮是否显示(canAdopt):', this.canAdopt)
          console.log('取消领养按钮是否显示(canCancelAdoption):', this.canCancelAdoption)
          
          this.fetchHealthRecords()
        } else {
          this.$message.error('获取宠物详情失败：' + response.message)
        }
      }).catch(error => {
        this.$message.error('获取宠物详情失败：' + error.message)
      }).finally(() => {
        this.loading = false
      })
    },
    fetchHealthRecords() {
      if (!this.pet.id) return
      this.healthRecordsLoading = true
      getHealthRecords(this.pet.id).then(response => {
        if (response.code === 200) {
          this.healthRecords = response.data || []
        } else {
          this.$message.error('获取健康记录失败：' + response.message)
        }
      }).catch(error => {
        this.$message.error('获取健康记录失败：' + error.message)
      }).finally(() => {
        this.healthRecordsLoading = false
      })
    },
    handleAdopt() {
      this.$confirm('确认申请领养该宠物吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        adoptPet(this.pet.id).then(response => {
          if (response.code === 200) {
            this.$message.success('申请领养成功')
            // 立即刷新宠物详情，并设置当前用户为主人
            this.pet.adoptionStatus = 'ADOPTED'
            this.pet.ownerId = this.userInfo.id
            this.pet.ownerName = this.userInfo.username
            
            // 完整刷新数据
            this.fetchPetDetail()
          } else {
            this.$message.error('申请领养失败：' + response.message)
          }
        }).catch(error => {
          this.$message.error('申请领养失败：' + error.message)
        })
      }).catch(() => {})
    },
    handleCancelAdoption() {
      this.$confirm('确认取消领养该宠物吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelAdoption(this.pet.id).then(response => {
          if (response.code === 200) {
            this.$message.success('取消领养成功')
            this.fetchPetDetail()
          } else {
            this.$message.error('取消领养失败：' + response.message)
          }
        }).catch(error => {
          this.$message.error('取消领养失败：' + error.message)
        })
      }).catch(() => {})
    },
    getImageUrl(path) {
      if (!path) {
        return '';
      }
      
      // 服务器地址
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果路径已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径以 / 开头
      if (!path.startsWith('/')) {
        path = '/' + path;
      }
      
      // 构建完整URL
      return serverUrl + path;
    }
  }
}
</script>

<style lang="scss" scoped>
.pet-detail-container {
  .clearfix {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .operation-buttons {
    .el-button {
      margin-left: 10px;
    }
  }

  .pet-image {
    width: 100%;
    height: 300px;
    margin-bottom: 20px;

    .el-image {
      width: 100%;
      height: 100%;
      border-radius: 8px;
    }
  }

  .pet-info {
    .pet-description {
      margin-top: 20px;
      
      h3 {
        margin-bottom: 10px;
        font-size: 16px;
        color: #333;
      }

      p {
        color: #666;
        line-height: 1.6;
      }
    }
  }

  .health-records {
    margin-top: 30px;

    h3 {
      margin-bottom: 15px;
      font-size: 16px;
      color: #333;
    }
  }
}
</style>